#include <stdio.h>
#include "uart_comp.h"
#include "esp_log.h"

#define UART_PORT_NUM UART_NUM_1 // 使用 UART1
#define UART_BAUD_RATE 115200
#define UART_TX_PIN (GPIO_NUM_22)
#define UART_RX_PIN (GPIO_NUM_23)
#define BUF_SIZE (1024)

static uart_receive_callback_t receive_callback = NULL;

void uart_receive_task(void *arg)
{
    uint8_t data[BUF_SIZE];
    while (1) {
        int len = uart_read_bytes(UART_PORT_NUM, data, BUF_SIZE, pdMS_TO_TICKS(20));
        if (len > 0) {
            data[len] = '\0'; 
            ESP_LOGI("UART", "Recv: %s", (char *)data);
            if (receive_callback) {
                receive_callback(data, len);
            }
        }else {
            vTaskDelay(pdMS_TO_TICKS(10)); // 避免空循环
        }
    }
}


void uart_init(uart_receive_callback_t callback)
{
    receive_callback = callback;
    const uart_config_t uart_config = {
        .baud_rate = UART_BAUD_RATE,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
        .source_clk = UART_SCLK_APB,
    };

    // 配置 UART 参数
    uart_driver_install(UART_PORT_NUM, BUF_SIZE * 2, 0, 0, NULL, 0);
    uart_param_config(UART_PORT_NUM, &uart_config);
    uart_set_pin(UART_PORT_NUM, UART_TX_PIN, UART_RX_PIN,
                 UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);

    // 启动接收任务
    xTaskCreate(uart_receive_task, "uart_receive_task", 4096, NULL, 10, NULL);
}



void uart_send_data(const char *data, size_t len)
{
    if (len == 0) {
        len = strlen(data);
    }
    uart_write_bytes(UART_PORT_NUM, data, len);
}





